from flask import Blueprint, jsonify, request, g
from app.err_no import errno_no
from loguru import logger
import json
import traceback
from app.db import dbDiningManage
from app.db.mongoClient import MongoError

blueprint = Blueprint('dining_manage', __name__, url_prefix='/api/dining')


@blueprint.route('v1/create', methods=['POST'])
def create():
    '''
    创建餐厅
    "menuInfo": [
		{
		    "menuName": "餐次名称",
            "mealStartTime": "餐次开始时间",
            "mealEndTime": "餐次结束时间",
            "bEnable": true/false, // 是否开启
		}
    ]
    '''
    try:
        j_data = json.loads(request.data)
        diningName = j_data.get('diningName')
        diningDesc = j_data.get('diningDesc')
        menuInfo = j_data.get('menuInfo')
        if diningName is None or len(diningName) <= 0 \
            or diningDesc is None \
            or menuInfo is None or len(menuInfo) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))
        
        bPass = True
        for v in menuInfo:
            menuName = v.get('menuName')
            if menuName is None or len(menuName) <= 0:
                bPass = False
                break
            if menuName == '早餐' or menuName == '午餐' or menuName == '晚餐' or menuName == '夜宵':
                pass
            else:
                bPass = False
                break
            mealStartTime = v.get('mealStartTime')
            mealEndTime = v.get('mealEndTime')
            bEnable = v.get('bEnable')
            if mealStartTime is None or mealEndTime is None or bEnable is None:
                bPass = False
                break
        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))
        
        res = dbDiningManage.createDining(diningName, diningDesc, menuInfo, g.userId)
        
        # 餐厅已经存在
        if res is False:   
            return jsonify(errno_no.ErrServerDocumentExist.data(None))
            
        return jsonify(errno_no.OK.data({'diningNo': res}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('v1/edit', methods=['POST'])
def dining_edit():
    '''
    编辑餐厅
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        diningName = j_data.get('diningName')
        diningDesc = j_data.get('diningDesc')
        menuInfo = j_data.get('menuInfo')
        if diningNo is None or len(diningNo) <= 0 \
            or diningName is None or len(diningName) <= 0 \
            or diningDesc is None \
            or menuInfo is None or len(menuInfo) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))
        
        bPass = True
        for v in menuInfo:
            menuName = v.get('menuName')
            if menuName is None or len(menuName) <= 0:
                bPass = False
                break
            if menuName == '早餐' or menuName == '午餐' or menuName == '晚餐' or menuName == '夜宵':
                pass
            else:
                bPass = False
                break
            mealStartTime = v.get('mealStartTime')
            mealEndTime = v.get('mealEndTime')
            bEnable = v.get('bEnable')
            if mealStartTime is None or mealEndTime is None or bEnable is None:
                bPass = False
                break
        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))    

        res = dbDiningManage.editDining(diningNo, diningName, diningDesc, menuInfo, g.userId)
        if res is False:
            return jsonify(errno_no.ErrServerDocumentExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('v1/del', methods=['POST'])
def dining_del():
    '''
    删除餐厅
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        if diningNo is None or len(diningNo) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDiningManage.delDining(diningNo)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        # 有档口的餐厅不允许删除
        if res is False:
            return jsonify(errno_no.ErrDiningDelForbid.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))